<template>
    <!-- 待签署合同 -->
    <div class="gd-main" style="background-color:#fff;">
        <div class="gd-body-side">
            <div class="md-1">
                <div class="md-1-item">
                    <div class="md-1-item-txt">甲方签署区</div>
                    <div @click="addJiafang" class="md-1-item-stamp clearfix" id="jiafangStamp"><img src="../../../../assets/images/jiafang.png" /></div>
                </div>
                <div class="md-1-item">
                    <div class="md-1-item-txt">乙方签署区</div>
                    <div @click="addYifang" class="md-1-item-stamp clearfix" id="yifangStamp"><img src="../../../../assets/images/yifang.png" /></div>
                </div>
                <el-row :gutter="10" style="margin-top:20px;">
                    <el-col :span="12"><el-button @click="save" style="width:100%;" type="primary">保存</el-button></el-col>
                    <el-col :span="12"><el-button @click="back" style="width:100%;" type="primary">返回</el-button></el-col>
                </el-row>
            </div>
        </div>
        <div class="gd-body-main md-2" id="md-2">
            <!-- 印章和页面仪器滚动 -->
            <div class="md-2-pdf" id="md-2-pdf"></div>
            <div class="md-2-stamp draggable" id="jiafangStampPdf"></div>
            <div class="md-2-stamp draggable" id="yifangStampPdf"></div>
        </div>
    </div>
</template>

<script>
    import {mapGetters} from 'vuex';
    import PDFJS from 'pdfjs-dist';
    import $ from 'jquery';
    //引入拖拽 - 全局 document 添加拖拽
    import '@/utils/drag';
    
    function throttle(method,context){
        var arg=Array.prototype.slice.call(arguments,2);
        clearTimeout(method.tId);
        method.tId=setTimeout(function(){
            method.apply(context,arg);
        },300);
    }     
    
    export default {
        props:['pdffile'],
        computed:{
            //登录后的数据在这里进行给实例赋值，就可以用 this.xxx 进行访问了
          ...mapGetters(['userId','currId','roleId','verificationStatus'])  
        },
        // 页面上需要展示的数据都要在 [data方法] 的 return 语句返回的对象里存在声明，否则会报错 
        data() {
            return {
                pdf:{
                    allPage:0,
                    width:0,//具体在前端操作时的 pdf 一页的宽与高 单位为 px 就不写了
                    height:0,
                    file:null//pdf 文件索引
                },
                jiafang:{ //存储位置信息
                    left:0,
                    top:0,
                    page:0,
                    drag:false,
                    hidden:true//是否为隐藏状态，也就是用户未设置
                },
                yifang:{
                    left:0,
                    top:0,
                    page:0,
                    drag:false,
                    hidden:true//是否为隐藏状态，也就是用户未设置
                }
            }
        },
        methods: {
            addJiafang(){
              var scrollTop = $('#md-2').prop('scrollTop');
                //隐藏状态
                if(this.jiafang.hidden){
                    this.jiafang.hidden = false;
                    $('#jiafangStampPdf').css({
                        display:'block'
                        ,left:(this.pdf.width - 160) / 2 + 'px'
                        ,top:scrollTop + ($('#md-2').height() - 160) / 2 + 'px'
                    });
                }else{
                    this.jiafang.hidden = true;
                    this.jiafang.drag = false;
                    $('#jiafangStampPdf').css({
                        display:'none'
                    });
                }  
            },
            addYifang(){
                var scrollTop = $('#md-2').prop('scrollTop');
                //隐藏状态
                if(this.yifang.hidden){
                    this.yifang.hidden = false;
                    $('#yifangStampPdf').css({
                        display:'block'
                        ,left:(this.pdf.width - 160) / 2 + 'px'
                        //当前视口的高
                        ,top:scrollTop + ($('#md-2').height() - 160) / 2 + 'px'
                    });
                }else{
                    this.yifang.hidden = true;
                    this.yifang.drag = false;
                    $('#yifangStampPdf').css({
                        display:'none'
                    });
                }
            },
            //保存
            save(){
              if(this.jiafang.hiddden == true || this.jiafang.drag == false){
                    this.$message({
                        type:'error',
                        message:'盖章区未设置'
                    });
                    return;
                }
                if(this.yifang.hiddden == true || this.yifang.drag == false){
                    this.$message({
                        type:'error',
                        message:'签字区未设置'
                    });
                    return;
                }
                //用户布置时的页面展示的 pdf 的具体宽度
                this.jiafang.width = this.yifang.width = this.pdf.width;
                console.log('盖章区： ',this.jiafang,'签字区: ',this.yifang);
                this.$emit('getarea',{
                    signatureAreaPage:this.jiafang.page,
                    width:this.jiafang.width,
                    signatureAreaPartyAX:this.jiafang.left,
                    signatureAreaPartyAY:this.jiafang.top,
                    signatureAreaPartyAWidth:160,
                    signatureAreaPartyAHeight:160,
                    signatureAreaPartyBX:this.yifang.left,
                    signatureAreaPartyBY:this.yifang.top,
                    signatureAreaPartyBWidth:160,
                    signatureAreaPartyBHeight:160
                });
            },
            //返回
            back(){
                this.$emit('hidepdf');
            },
            // pdf 文件加载---------------------
            getPdf:function(){
                PDFJS.getDocument(this.pdffile).then(file => {
                    //存储 pdf 文件引用
                    this.pdf.file = file;
                    //存储总页数
                    this.pdf.allPage = file.numPages;
                    console.log('file对象 ',file);
                    var html = '';
                    for(var i = 1; i <= this.pdf.allPage; i++) {
                        html += '<canvas class="canvas" id="canvas' + i + '"></canvas>';
                    }
                    $('#md-2-pdf').append(html);
                    this.renderPage(1);
               });
            },
            //渲染 pdf 为 canvas
            renderPage:function(pageNum){
                this.pdf.file.getPage(pageNum).then(page => {
                    var canvas = document.getElementById('canvas' + pageNum),
                        ctx = canvas.getContext('2d'),
                        viewport = page.getViewport(2);
                    console.log('文件原始尺寸',viewport);
                    //设置尺寸
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    //设置为宽度自适应
                    canvas.style.width = '100%';
                    //存储 pdf 加载时的宽度
                    this.pdf.width = $('#md-2').width();
                    //宽度设置为固定宽，方便计算，服务器需要的时候把宽度和高度回传回去 
                    this.pdf.height = parseInt((viewport.height / viewport.width) * this.pdf.width);
                    canvas.style.height = this.pdf.height + 'px';
                    
                    var renderContext = {
                        canvasContext: ctx,
                        viewport: viewport
                    };
                    
                    page.render(renderContext);
                    
                    //循环一次渲染完
                    if(pageNum < this.pdf.allPage){
                        this.renderPage(pageNum + 1);
                    }
                });
            },
            //进行各项值重置   jiafang & yifang : width,left,top pdf = width ,每个 canvas 的 height
            resize:function(){
                //新的 width
                var scale = $("#md-2").width()  / this.pdf.width;
                console.log('缩放比例',scale);
                //更新 pdf.width
                this.pdf.width = parseInt(this.pdf.width * scale);
                //更新 pdf.height
                this.pdf.height = parseInt(this.pdf.height * scale);
                //更新 canvas
                $('.canvas').css({
                    height:this.pdf.height + 'px'
                });
                //更新印章
                if(this.jiafang.hidden == false){
                    this.jiafang.left = parseInt(this.jiafang.left * scale);
                    $('#jiafangStampPdf').css({
                        left:this.jiafang.left + 'px'
                    });
                    this.jiafang.top = parseInt(this.jiafang.top * scale);
                    console.log('窗口变化后：',$('#jiafangStampPdf').css('top'));
                    $('#jiafangStampPdf').css({
                        top:parseInt($('#jiafangStampPdf').css('top')) * scale + 'px'
                    });
                    console.log('重新设置：',$('#jiafangStampPdf').css('top'));
                }
                //更新签字区
                if(this.yifang.hidden == false){
                    this.yifang.left = parseInt(this.yifang.left * scale);
                    $('#yifangStampPdf').css({
                        left:this.yifang.left + 'px'
                    });
                    this.yifang.top = parseInt(this.yifang.top * scale);
                    $('#yifangStampPdf').css({
                        top:parseInt($('#yifangStampPdf').css('top')) * scale + 'px'
                    });
                }
            }
        },
        beforeDestroy(){
            $(window).unbind('resize');
        },
        mounted(){
            console.log('pdf文件: ',this.pdffile);
            //加载 pdf
            this.getPdf();
            //绑定拖拽
            drag.on('dragstart draging dragend',e => {
                var //diff偏移
                    diff,
                    //被拖拽元素相对于文档的距离 [ 不受滚动影响 ] [ 前提页面不能存在滚动 ]
                    //更改： 由距离文档的距离，改为 距离视口的距离 方便统一管理计算，e.clientX/Y 同类型
                    offset,
                    //被拖拽元素相对于距离视口的距离 [ 受到滚动影响 ]
                    cOffset,
                    //被拖动元素距离包含元素的距离
                    rOffset,
                    rangeElm = document.getElementById('md-2-pdf'),
                    scrollElm = document.getElementById('md-2'),
                    //获取 clientX/Y 的移动范围 [ 可移动的范围 ]
                    clientRange,
                    //被拖拽的当前元素
                    target = e.target;
                if(e.type == 'dragstart'){
                    clientRange = rangeElm.getBoundingClientRect();
                }
                switch(e.type){
                    case 'dragstart':
                        offset = target.getBoundingClientRect();
                        //获取距离视口的距离
                        cOffset = {
                            x:offset.left,
                            y:offset.top
                        };
                        rOffset = {
                            x:target.offsetLeft,
                            y:target.offsetTop
                        };
                        //偏移量
                        diff = {
                            x: e.clientX - cOffset.x,
                            y: e.clientY - cOffset.y
                        };
                        
                        //将除初始值保存到对象属性
                        target.clientRange = clientRange;
                        target.diff = diff;
                        break;
                    case 'draging':
                        if(e.clientX > target.clientRange.left && e.clientX < target.clientRange.right){
                            target.style.left = (e.clientX - target.clientRange.left - target.diff.x) + 'px';
                        }
                        if(e.clientY > target.clientRange.top && e.clientY < target.clientRange.bottom){
                            target.style.top = (e.clientY - target.clientRange.top - target.diff.y) + 'px';
                        }
                        break;
                    case 'dragend':
                        console.log(this.pdf.height);
                        var $target = $(target),
                            //上滚动的距离
                            offsetTop = target.offsetTop,
                            top = offsetTop % this.pdf.height,//距离当前页的 上 距离
                            left = e.clientX - target.clientRange.left - target.diff.x,//距离当前页的 左 距离
                            page = parseInt(offsetTop / this.pdf.height) + 1,
                            which;
                        if($target.prop('id') == 'jiafangStampPdf'){
                            which = this.jiafang;
                        }else{
                            which = this.yifang;
                        }
                        which.left = left;
                        which.top = top;
                        which.page = page;
                        which.drag = true;
                        break;
                }
            });
            
            //窗口变动需要更新的值
            $(window).resize(() => {
                throttle(this.resize,this);
            });
        }
    }
</script>

<style lang="less" scoped>
.gd-body-side{float:left;width:200px;height:~'calc(100vh - 90px)';position:relative;background-color:#eee;}
.gd-body-main{margin-left:200px;height:~'calc(100vh - 90px)';background-color:green;}
/* 模块 */
.md-1{font-size:20px;text-align:center;/*position:relative;top:50%;margin-top:-235px;*/}
.md-1-item{width:160px;margin:0 auto;}
.md-1-item-txt{height:40px;line-height:40px;}
.md-1-item-stamp{width:80px;height:80px;margin:0 auto;cursor:pointer;}
.md-1-item img{float:left;width:100%;height:100%;}

.md-2{
    font-size:20px;background-color:silver;position:relative;
    overflow:hidden;overflow-y:auto;
}
.md-2-stamp{position:absolute;}

#jiafangStampPdf,#yifangStampPdf{width:160px;height:160px;display:none;position:absolute;cursor:pointer;background-size:100% 100%;}
#jiafangStampPdf{background-image:url(../../../../assets/images/jiafang.png);}
#yifangStampPdf{background-image:url(../../../../assets/images/yifang.png);}
</style>